import {ListModel, Me, Model, ModelClazz, Net, Plugin} from "foundation";
import {WXDBManager, WXHttpBuilderCreator} from "MVx"
import {BaseUrl} from "./config";
import {RegisterAutoLogin} from "./api/RegisterAutoLogin";

export class MainApp {
  private static registered: boolean = false;
  private static pluginName_: string = "MainApp";

  public static plugin(): Plugin {
    if (this.registered) {
      return Plugin.getBy(this.pluginName_)
    }

    Plugin.register(this.pluginName_);
    let plugin = Plugin.getBy(this.pluginName_);
    plugin.setDBManager(new WXDBManager(plugin));

    let mainNet = new Net(plugin, BaseUrl);
    mainNet.setToMainNet();
    plugin.setMainNet(mainNet);

    mainNet.setHttpBuilderCreator(WXHttpBuilderCreator());

    RegisterAutoLogin(mainNet);

    this.registered = true;

    return plugin;
  }


  public static async getModel<T extends Model>(modelClazz: ModelClazz<T>): Promise<T> {
    return (await MainApp.plugin().mf().getModel(modelClazz))
  }

  public static async me(): Promise<string> {
    return (await (await MainApp.plugin().mf().getModel(Me)).uid())
  }

  public static async listModel(): Promise<ListModel> {
    return (await MainApp.plugin().mf().getModel(ListModel))
  }
}
